<template>
    <div class="search-container">
         <el-input
            v-model="filterParams.keyword"
            placeholder="请输入小区名称"
            style="width: 200px"
            class="filter-item"
            clearable
            @change="emitFilterChange"
          />
          <el-button
            class="filter-item"
            type="primary"
            :icon="Plus"
            @click="handleCreate"
          >
            新增
          </el-button>
          <el-button
            class="filter-item"
            type="primary"
            :icon="Search"
            @click="handleSearch"
          >
            搜索
          </el-button>
        </div>
        <el-table
          :data="tableData"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="小区名称" prop="name" min-width="160" />
          <el-table-column label="所属区域" prop="regionText" min-width="200" />
          <el-table-column label="详细地址" prop="address" min-width="200" />
          <el-table-column label="小区类型" prop="type" width="100" align="center" />
          <el-table-column label="建造时间" prop="buildYear" width="100" align="center" />
          <el-table-column label="老旧小区改造情况" prop="renovation" min-width="160" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)" />
              <el-popconfirm title="确定删除该数据吗？" @confirm="handleDelete(row)">
                <template #reference>
                  <el-button size="small" type="danger" :icon="Delete" />
                </template>
              </el-popconfirm>
              <el-button type="info" size="small" :icon="Document" @click="handleDetail(row)" />
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="pagination.total"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          @update:current-page="handleCurrentChange"
          @update:page-size="handlePageSizeChange"
        />
        <OnsiteSurveyDialog
          v-model="dialogVisible"
          :mode="dialogMode"
          :formData="currentForm"
          :typeOptions="typeOptions"
          :regionOptions="regionOptions"
          :rules="rules"
          @ok="handleDialogOk"
          @cancel="handleDialogCancel"
        />
  </template>
  
  <script setup lang="ts">
  import { ref, reactive } from 'vue'
  import Pagination from '@/components/Pagination/index.vue'
  import { Delete, Edit, Plus, Search, Document } from '@element-plus/icons-vue'
  import guangzhouAreaData from '@/utils/guangzhou-area.json'
  import type { CommunityData } from '@/types/community'
  import OnsiteSurveyDialog from './OnsiteSurveyDialog.vue'
  import { useOnsiteSurveyStore } from '@/stores/onsiteSurvey'
  const onsiteSurveyStore = useOnsiteSurveyStore()

  
  // 定义类型接口
  interface Building {
    buildingNo: string
    unitCount: number
    buildYear: string
    floorCount: number
    population: number
    elderPopulation: number
  }
  
  const filterParams = reactive({
    keyword: '',
  })
  
  const dialogVisible = ref(false)
  const dialogMode = ref<'add' | 'edit' | 'detail'>('add')
  const currentForm = ref<CommunityData>({
    id: undefined,
    name: '',
    region: [],
    type: '',
    buildYear: '',
    renovation: '',
    buildings: [],
    address: ''
  })

  const rules = reactive({
    name: [{ required: true, message: '请输入小区名称', trigger: 'blur' }],
    region: [{ required: true, message: '请选择所属区域', trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    type: [{ required: true, message: '请选择小区类型', trigger: 'change' }],
    buildYear: [{ required: true, message: '请选择建造时间', trigger: 'change' }],
    renovation: [{ required: true, message: '请填写改造情况', trigger: 'blur' }]
  })
  
  const typeOptions = ['商品房', '保障房', '自建房', '老旧小区', '其他']
  const regionOptions = guangzhouAreaData

  // 根据区域代码数组获取区域文本
  const getRegionText = (regionCodes: string[]) => {
    if (!regionCodes || regionCodes.length === 0) return ''
    
    const findLabel = (options: any[], codes: string[], index: number): string => {
      if (index >= codes.length) return ''
      const option = options.find(item => item.value === codes[index])
      if (!option) return ''
      return option.label + (index < codes.length - 1 ? ' / ' : '') + findLabel(option.children || [], codes, index + 1)
    }
    
    return findLabel(regionOptions, regionCodes, 0)
  }

  const tableData = ref<CommunityData[]>([])
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  const mockData: CommunityData[] = onsiteSurveyStore.getData

  const fetchData = async () => {
    let filtered = mockData.filter(item => {
      let match = true
      if (filterParams.keyword) match = match && item.name.includes(filterParams.keyword)
      return match
    })
    // 展示用：拼接regionText
    filtered.forEach(item => {
      item.regionText = getRegionText(item.region)
    })
    tableData.value = filtered
    pagination.total = filtered.length
  }

  const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    fetchData()
  }

  const handlePageSizeChange = (size: number) => {
    pagination.pageSize = size
    fetchData()
  }

  const emitFilterChange = () => {
    fetchData()
  }

  const handleCreate = () => {
    dialogMode.value = 'add'
    currentForm.value = {
      id: undefined,
      name: '',
      region: [],
      type: '',
      buildYear: '',
      renovation: '',
      buildings: [],
      address: ''
    }
    dialogVisible.value = true
  }

  const handleEdit = (row: CommunityData) => {
    dialogMode.value = 'edit'
    currentForm.value = { ...row }
    dialogVisible.value = true
  }

  const handleDetail = (row: CommunityData) => {
    dialogMode.value = 'detail'
    currentForm.value = { ...row }
    dialogVisible.value = true
  }

  const handleDialogOk = (form: CommunityData) => {
    if (dialogMode.value === 'add') {
      form.id = Date.now()
      tableData.value.push({ ...form })
    } else if (dialogMode.value === 'edit') {
      tableData.value = tableData.value.map(item => item.id === form.id ? { ...form } : item)
    }
    fetchData()
  }

  const handleDialogCancel = () => {}

  const handleDelete = (row: CommunityData) => {
    tableData.value = tableData.value.filter((item: CommunityData) => item.id !== row.id)
    fetchData()
  }

  const handleSearch = () => {
    console.log('搜索小区')
  }

  fetchData()
</script>
<style scoped lang="scss">
.search-container {
     margin-bottom: 20px;
    
    .filter-item {
      margin-right: 10px;
    }
}
</style>